#pragma once
#include<iostream>
#include<string>
#include<cstring>

#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>

#include"Logger.hpp"
#include"Comm.hpp"

const int glistendefault=-1;
const uint16_t _port=8888;
const int gbacklog=8;

class TcpServer
{
public:
    TcpServer(const uint16_t&port)
        :_port(port),
        _listenfd(glistendefault)
    {}
    void Init()
    {
        int _listenfd=socket(AF_INET,SOCK_STREAM,0);
        if(_listenfd<-1)
        {
            LOG(Loglevel::FATAL) << "create tcp socket error";
            exit(SOCKET_CREAT_ERROR);
        }
        LOG(Loglevel::INFO) << "create tcp socket success "<<_listenfd;

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=htonl(INADDR_ANY);

        if(bind(_listenfd,(struct sockaddr*)&local,sizeof(local))!=0)
        {
            LOG(Loglevel::FATAL) << "bind socket error"<<_listenfd;
            exit(SOCKET_BIND_ERROR);
        }
        LOG(Loglevel::INFO) << "bind socket success";

        if(listen(_listenfd,gbacklog)!=0)
        {
            LOG(Loglevel::FATAL) << "listen socket error";
            exit(SOCKET_LISTEN_ERROR);
        }
        LOG(Loglevel::INFO) << "listen socket success"<<_listenfd;
    }
    void Start()
    {
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sockfd=accept(_listenfd,(struct sockaddr*)&peer,&len);
            if(sockfd < 0)
            {
                LOG(Loglevel::WARNING) << "accept client error";
                continue;
            }
            LOG(Loglevel::INFO)<<"获取链接成功："<<_listenfd;
        }
    }
    ~TcpServer()
    {}
private:
    int _listenfd;
    uint16_t _port;
};